package net.chrone.quickpayapi.task;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import net.chrone.quickpayapi.api.CiticApi;
import net.chrone.quickpayapi.model.PayforTxn;
import net.chrone.quickpayapi.service.PayforService;
import net.chrone.quickpayapi.service.RedisService;
import net.chrone.quickpayapi.util.Constant;

/**
 * 定时付款交易任务
 * @author Jerry
 *
 */
@Component
public class PayforTxnTask {
	
	private final  Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private PayforService payforService;
	@Autowired
	private RedisService redisService;

	
	/**
	 * 银商
	 */
	@Scheduled(cron="0 0/1 * * * ?")
	public void citic(){
		logger.debug("扫描银商待发送交易");
		List<PayforTxn> payfors = payforService.findAllNewPayTxn(Constant.CHNL_CODE_CITIC,10);//获取所有待付款交易
		for(PayforTxn payfor:payfors){
			logger.debug("txn_id:"+payfor.getTxnId()+" 发送代付");
			String respInfo = CiticApi.payfor(payfor,redisService);
			String code = respInfo.split(":")[0];
			String info = respInfo.split(":")[1];
			if(StringUtils.isNotEmpty(respInfo)){//有应答
				payfor.setRespCode(code);
				payfor.setRespDesc(info);
				if("000000".equals(code)){//000000是交易成功;PB0098是交易失败;PB0099是处理中 
					payfor.setPaySt(Constant.PAYFOR_ST_PAING);
					payfor.setDestTxnId(payfor.getTxnId());//银商不返回它的ID，这里直接用自己的ID填充
				}else{
					payfor.setPaySt(Constant.PAYFOR_ST_FAIL);
				}
			}else{//没有应答
				payfor.setPaySt(Constant.PAYFOR_ST_PAING);
			}
			payforService.updateByPrimaryKey(payfor);
		}
	}
	
}
